<template>
  <div :class="animate" :style="{ height: height, width: width}" :id="chartOption.bindingDiv">
    <div class="demo-input-suffix" ref="text">
      <label class="el-form-item__label" for="" :style="normalTextStyle">{{this.chartOption.label.context}}</label>
      <div class="el-form-item__content">

        <el-input placeholder="请输入" class="eleInput" v-model="input" :style="inputStyle" :id="inputId" :name="this.chartOption.input.name" @blur.prevent="renderChart"
        :type="this.chartOption.input.type" :maxlength="this.chartOption.input.maxlength" @change="renderChart"></el-input>
      </div>
      
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from '@/views/dashboard/mixins/resize'

import '../../animate/animate.css'

import {parseQueryString, fIsUrL} from '../../util/urlUtil'
import { remoteChartApi } from '@/api/tool/datav/chartApi'
import { bindChart} from "../../util/LinkageChart";
import { chartApiBar } from "@/api/tool/datav/chartApi";
import { websocketCommand } from "../../util/websocket.js";

const animationDuration = 6000;

export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    chartOption: {
      type: Object,
    },
    drawingList:{
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      //dataOption: this.chartOption
      input: '',
      timer: "",
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
    };
  },
  watch: {
    width() {
      
    },
    height() {
      
    },
    chartOption: {
      deep: true,
      handler(newVal) {
        this.setOptions(JSON.parse(JSON.stringify(newVal)));
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        }
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    this.chart = null;
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  computed:{
    normalTextStyle(){
      const style = {color:this.chartOption.label.fontColor,fontSize:this.chartOption.label.fontSize + "px",fontFamily:this.chartOption.label.fontFamily}
      return style
    },
    inputId(){
      return 'input' + this.chartOption.bindingDiv
    },
    inputStyle(){
      const style = {color:'#fff',borderRadius:'5px',borderColor:'rgba(255,255,255,0.8)',backgroundColor:'rgba(0,0,0,0)',
      fontSize:this.chartOption.label.fontSize + "px",fontFamily:this.chartOption.label.fontFamily,width:this.chartOption.width+"px"}

      return style
    }
  },
  methods: {
    initChart() {
      
      //判断是否开启定时器，当是访问url接口时候并且timeout不为0时候开启定时器
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
           
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
      
    },
    setOptions: async function(dataOption) {
      //初始化数据
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url" || dataOption.isStaticData == false) {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;

        let result = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
        dataOption.staticDataValue = result;

      } else if (dataOption.dataSourceType == "database") {
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;
          }
        }
      }
      //数据处理
       if(dataOption.customData != undefined && dataOption.customData != ""){
          
          try {
             dataOption.staticDataValue = (
          
            //里面为要处理的代码块
            eval(dataOption.customData) 
            
            )(
              dataOption.staticDataValue,
              this.$refs.text
            );
          } catch (error) {
            console.log(error)
          }
          
       }
       //交互组件配置
       if(dataOption.interactData != undefined && dataOption.interactData != ""){
          
          try {
             dataOption.staticDataValue = (
          
            //里面为要处理的代码块
            eval(dataOption.interactData) 
            
            )(
              dataOption.staticDataValue,
              this.$refs.text
            );
          } catch (error) {
            console.log(error)
          }
         
       }
    },
    renderChart(){

      //获取与input绑定的图表，传递参数，重新渲染
      let bindList = this.chartOption.bindList;
      let name = this.chartOption.input.name;
      if(bindList.length > 0){

        bindChart(name, this.input, bindList,this.drawingList)

        // let exclusion = ["input","timeframe", "select", "cascade","tab","textCheckBox","timeline"];
        // let renderCharts = this.drawingList.filter(item => { 
        //   return bindList.indexOf(item.chartOption.bindingDiv) > -1 && exclusion.indexOf(item.type) == -1
        // })
        // //遍历绑定组件
        // renderCharts.forEach(item => {

          
        //    //获取组件参数
        //   let requestParameters = item.chartOption.requestParameters;

        //   //如果已经包含该名称的参数则替换
        //   if(requestParameters != "" && requestParameters.indexOf(name) != -1){
        //     //拆分成数组
        //     let paramArr = requestParameters.split('&');
        //     //获取到包含该名称的数组项
        //     for(let i in paramArr){
        //        if(paramArr[i].indexOf(name) != -1){
        //          //替换位=为当前内容
        //         paramArr.splice(i,1,name + "=" + this.input)
               
        //       }
        //     }
        //      //将数组重新按照&符号拼接为字符串
        //     requestParameters = '&' + paramArr.join("&")
            
        //   }else{
        //     //如果为新名称参数直接拼在结尾
        //     requestParameters += "&"+this.chartOption.input.name + "=" + this.input;
        //   }
        //   //判断参数是否已&符号开始，是则删除该符号
        //   if(requestParameters.indexOf('&') == 0){
        //     item.chartOption.requestParameters = requestParameters.substring(1, requestParameters.length);
        //   }else{
        //     //给绑定组件重新赋值参数渲染组件
        //     item.chartOption.requestParameters = requestParameters
        //   }
         
          
        // });

      }
      //远程控制组件
     if(this.chartOption.isRemote == true){
        if(this.chartOption.remote != undefined && this.chartOption.remote != null){
          let remoteData = { ...this.chartOption.remote };
          let queryObj = {};
          queryObj[this.chartOption.input.name] = this.input;
          remoteData.query = queryObj;
          //调用接口
          remoteChartApi(remoteData)
        }
     }
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = e.result;
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }
  }
};
</script>

<style lang="scss" scoped>
.demo-input-suffix{
  display: flex;
  float: left;
}
/deep/ .eleInput .el-input--medium .el-input__inner {
    height: 36px;
    line-height: 36px;
    background-color: #ffffff;
}
/deep/ .eleInput .el-input__inner {
    background-color: #ffffff !important;
    color: #000 !important;
}
</style>
